package com.nbsaas.boot.product.ext.resource;

import com.nbsaas.boot.product.api.apis.ProductApi;
import com.nbsaas.boot.product.api.apis.ProductVisitApi;
import com.nbsaas.boot.product.api.domain.field.ProductVisitField;
import com.nbsaas.boot.product.api.domain.request.ProductVisitRequest;
import com.nbsaas.boot.product.api.domain.response.ProductResponse;
import com.nbsaas.boot.product.api.domain.response.ProductVisitResponse;
import com.nbsaas.boot.product.ext.apis.ProductVisitExtApi;
import com.nbsaas.boot.rest.filter.Filter;
import com.nbsaas.boot.rest.response.ResponseObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service
public class ProductVisitExtResource implements ProductVisitExtApi {

    @Resource
    private ProductVisitApi productVisitApi;

    @Resource
    private ProductApi productApi;

    @Transactional
    @Override
    public ResponseObject<?> visit(ProductVisitRequest request) {
        ResponseObject<?> result = new ResponseObject<>();
        if (request.getCreator() == null) {
            result.setCode(501);
            result.setMsg("请先登录");
            return result;
        }
        if (request.getProduct() == null) {
            result.setCode(502);
            result.setMsg("请选择商品");
            return result;
        }
        ProductResponse product = productApi.oneData(Filter.eq("id", request.getProduct()));
        if (product == null) {
            result.setCode(503);
            result.setMsg("商品不存在");
            return result;
        }
        request.setShop(product.getShop());

        Long num = productVisitApi.countData(
                Filter.eq(ProductVisitField.creator, request.getCreator()),
                Filter.eq(ProductVisitField.product, request.getProduct()),
                Filter.eq(ProductVisitField.shop, request.getShop())
        );
        if (num == null) {
            num = 0L;
        }
        if (num == 0) {
            return productVisitApi.create(request);
        } else {
            ProductVisitResponse productVisit = productVisitApi.oneData(
                    Filter.eq(ProductVisitField.creator, request.getCreator()),
                    Filter.eq(ProductVisitField.product, request.getProduct()),
                    Filter.eq(ProductVisitField.shop, request.getShop())
            );
            if (productVisit != null) {
                request.setId(productVisit.getId());
                return productVisitApi.update(request);
            }

        }

        return result;
    }
}
